package com.yueguang.springai.service;

import com.yueguang.springai.config.OrderEvents;
import com.yueguang.springai.config.OrderStatus;
import com.yueguang.springai.model.param.Order;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.persist.StateMachinePersister;
import org.springframework.stereotype.Component;

@Component("orderProcessor")
@Slf4j
public class OrderProcessor {

    @Resource
    private StateMachine<OrderStatus, OrderEvents> orderStateMachine;

    @Resource
    private StateMachinePersister<OrderStatus, OrderEvents, Order> persister;

    public  Boolean process(Order order, OrderEvents event){
        Message<OrderEvents> message = MessageBuilder.withPayload(event)
                .setHeader("order", order).build();
        return sendEvent(message);
    }

    @SneakyThrows
    private boolean sendEvent(Message<OrderEvents> message) {
        Order order = (Order) message.getHeaders().get("order");
        persister.restore(orderStateMachine, order);
        boolean result = orderStateMachine.sendEvent(message);
        return result;
    }
}
